import * as types from "../types";
import * as api from "../../http/admin-api";
import that from "../../main";
import { Message } from "element-ui";
import { routerControl } from "../../router.js";

const state = {
    userInfo: {},
    menuList: [],
    uploadUrl: "",
    isChange: false
};

const mutations = {
    [types.LOG_GETUSERINFO](state, status) {
        state.userInfo = Object.assign({}, status);
    },
    [types.INDEX_GETMENULIST](state, status) {
        state.menuList = [...status];
    }
};

const getters = {
    userInfo: state => state.userInfo,
    roles: state => state.userInfo.user_type
};

const actions = {
    /**
     * 获取用户信息
     */
    getUserInfo({ commit, dispatch, rootState }, isRefresh) {
        api.getUserInfo().then(res => {
            if (res) {
                sessionStorage.setItem(
                    "userInfo",
                    JSON.stringify(res.bus_json.user_id)
                );
                commit(types.LOG_GETUSERINFO, res.bus_json);
                if (res.bus_json.is_default_pwd !== "1") {
                    if (res.bus_json.sys_codes) {
                        dispatch(
                            "getMenuListByRoles",
                            res.bus_json.sys_codes[0].sys_code
                        );
                    } else {
                        Message({
                            message: "您没有权限，请联系管理员！",
                            type: "warning"
                        });
                    }
                }

                dispatch("getCodeList");
            }
        });
    },
    /**
     * 获取菜单列表
     */
    getMenuListByRoles({ commit, state }, sysId) {
        api.getMenuListByRoles({
            sys_code: sysId
        }).then(res => {
            if (res) {
                let menuList = res.bus_json;
                routerControl(menuList);
                let activeTab = sessionStorage.getItem("activeTab");
                let path = "";
                if (menuList && menuList[0] && menuList[0].childlist) {
                    if (menuList[0].childlist[0].childlist) {
                        path = menuList[0].childlist[0].childlist[0].route_path;
                    } else {
                        path = menuList[0].childlist[0].route_path;
                    }
                } else {
                    path = menuList[0].route_path;
                }

                commit(types.INDEX_GETMENULIST, res.bus_json);

                if (activeTab && activeTab.length) {
                    that.$router.push("/" + activeTab);
                } else {
                    that.$router.push(path);
                }
            }
        });
    }
};

export default {
    state,
    actions,
    getters,
    mutations
};
